package com.example.myapplication;

import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.ColorSpace;
import android.graphics.Paint;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.util.Objects;

public class MainActivity2 extends AppCompatActivity {

    Bitmap originBitmap;
    ImageView imageView;
    EditText alphaEditText;
    ColorSpace colorSpace;
    TextView colorSpaceDescText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main2);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        CheckAndOpenP3();

        imageView = findViewById(R.id.image_view);
        alphaEditText = findViewById(R.id.alpha_edit_text);
        colorSpaceDescText = findViewById(R.id.image_desc_text);
        findViewById(R.id.create_new_image).setOnClickListener(this::CreateNewImage);

        RadioGroup colorSpaceGroup = findViewById(R.id.color_space_group);
        colorSpaceGroup.setOnCheckedChangeListener((group, checkedId) -> {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                if (checkedId == R.id.color_space_srgb) {
                    colorSpace = ColorSpace.get(ColorSpace.Named.SRGB);
                } else if (checkedId == R.id.color_space_p3) {
                    colorSpace = ColorSpace.get(ColorSpace.Named.DISPLAY_P3);
                }
            }
        });

        new Handler().postDelayed(() -> {
            originBitmap = DecodePicture(getResources(), R.drawable.haidishanhuxiao, imageView.getWidth(), imageView.getHeight());
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                colorSpace = originBitmap.getColorSpace();
            }
            ShowImage(originBitmap);
        }, 100);
    }

    void CreateNewImage(View view) {
        String inputAlpha = alphaEditText.getText().toString();
        float alpha = 1;
        if (!inputAlpha.isEmpty()) {
            alpha = Float.parseFloat(inputAlpha);
        }
        if (alpha < 0) {
            alpha = 0;
        }
        if (alpha > 1) {
            alpha = 1;
        }
        Bitmap bitmap = CreateNewBitmap(originBitmap, colorSpace, alpha);
        ShowImage(bitmap);
    }

    void ShowImage(Bitmap bitmap) {
        imageView.setImageBitmap(bitmap);
        if (bitmap != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            ColorSpace colorSpace = bitmap.getColorSpace();
            if (colorSpace != null) {
                colorSpaceDescText.setText("图片色域：" + colorSpace.getName());
            }
        }
    }

    Bitmap CreateNewBitmap(Bitmap source, ColorSpace colorSpace, float alpha) {
        if (source == null || Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            return null;
        }
        int[] pixels = new int[source.getWidth() * source.getHeight()];
        source.getPixels(pixels, 0, source.getWidth(), 0, 0, source.getWidth(), source.getHeight());
        for (int i = 0; i < pixels.length; i++) {
            int newAlpha = (int) (Color.alpha(pixels[i]) * alpha);
            int red = Color.red(pixels[i]);
            int green = Color.green(pixels[i]);
            int blue = Color.blue(pixels[i]);
            pixels[i] = Color.argb(newAlpha, red, green, blue);
        }
        Bitmap newBitmap = Bitmap.createBitmap(
                source.getWidth(),
                source.getHeight(),
                Bitmap.Config.ARGB_8888,
                true,
                colorSpace);
        newBitmap.setPixels(pixels, 0, newBitmap.getWidth(), 0, 0, newBitmap.getWidth(), newBitmap.getHeight());
        return newBitmap;
    }

    public Bitmap DecodePicture(Resources res, int resId, int width, int height) {
        // 预解码获取元数据
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res, resId, options);

        // 实际解码图片数据
        options.inJustDecodeBounds = false;
        options.inSampleSize = Math.min(options.outWidth/width, options.outHeight/height);
        return BitmapFactory.decodeResource(res, resId, options);
    }

    void CheckAndOpenP3() {
        TextView systemVersionText = findViewById(R.id.system_version_text);
        TextView supportP3Text = findViewById(R.id.support_p3_text);

        boolean screenWideColorGamut = false;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            systemVersionText.setText("系统版本：Android 11及以上");
            screenWideColorGamut = Objects.requireNonNull(getDisplay()).isWideColorGamut();
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            systemVersionText.setText("系统版本：Android 8.0 ~ Android 11");
            screenWideColorGamut = getResources().getConfiguration().isScreenWideColorGamut();
        } else {
            systemVersionText.setText("系统版本：Android 8.0以下");
        }
        if (screenWideColorGamut) {
            supportP3Text.setText("是");
            supportP3Text.setTextColor(Color.GREEN);
            openP3(); // 窗口设置P3
        } else {
            supportP3Text.setText("否");
            supportP3Text.setTextColor(Color.RED);
        }
    }

    void openP3() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            getWindow().setColorMode(ActivityInfo.COLOR_MODE_WIDE_COLOR_GAMUT);
            if (getWindow().getColorMode() == ActivityInfo.COLOR_MODE_WIDE_COLOR_GAMUT) {
                TextView windowOpenP3 = findViewById(R.id.window_open_p3_text);
                windowOpenP3.setText("是");
                windowOpenP3.setTextColor(Color.GREEN);
            }
        }
    }

}